define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require("dialogplus");
    var util = require("util");
    var ui = require("ui");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var config = require('/public/js/myservice/config');
    var myMath = require('/public/js/myservice/common/my-math');
    var refundCtrl = require('/public/js/myservice/confirm/confirm-refund-ctrl');
    require("pagination");
    require("angular-ui");
    require("uploader");
    require('/public/js/myservice/common/nav');
    require('/public/js/myservice/contract/contract-common');

    angular.module('Confirm', ['ngUI', 'myNav'])
        .controller('confirmCtl',['$scope', 'appservice', 'confirmRefundService', function ($scope, appservice, confirmRefundService) {
            $scope.confirmRefundService = confirmRefundService;

            //console.log($scope.confirmRefundService);
            $scope.test = 'test';

            appservice.name = '明源云链-确认回款';
            //合同列表
            $scope.contracts = [];

            $scope.pname = '';

            //筛选列表
            $scope.pay_way = [{
                name: '全部', selected: true, value: ''
                }, {
                    name: '支付宝', selected: false, value: '支付宝'
                },{
                    name: '微信', selected: false, value: '微信'
                }
            ];

            $scope.product_name = [{
                name: '全部', selected: true, value: ''
            }, {
                name: '移动工程协同充值卡', selected: false, value: '移动工程协同充值卡'
            }, {
                name: '云采购采宝', selected: false, value: '云采购采宝'
            }, {
                name: '云采购会员', selected: false, value: '云采购会员'
            }, {
                name: '云采购对接会', selected: false, value: '云采购对接会'
            }, {
                name: '垂直门户', selected: false, value: '垂直门户'
            }];

            $scope.refund_status = [{
                name: '未确认回款', selected: true, value: '0'
            },{
                name: '已确认回款', selected: false, value: '1'
            }
            ];

            // 支付时间默认值初始化
            var beginDate = new Date();
            beginDate.setDate(1);
            $scope.beginDate = util.formatDate(beginDate, 'yyyy-MM-dd');

            var endDate = new Date();
            $scope.endDate = util.formatDate(endDate, 'yyyy-MM-dd');
            // 确认回款按钮控制
            $scope.confirmDisabled = false;
            $scope.total_pay_amount = 0;

            //$scope.getFilterDataNature = function(){
            //    var url = api_prefix + "contract/get-contract-natures";
            //
            //    $.ajax({
            //        url: url,
            //        type: 'get',
            //        dataType: 'json',
            //        success: function(res){
            //            if(res.retCode === "0"){
            //                var items = res.data;
            //                var tabData = [{value: '', name: '全部', selected: true}];
            //                var item;
            //                for (var i = 0; item = items[i]; i++) {
            //                    tabData.push({
            //                        value: item.property_id + '',
            //                        name: item.property_name
            //                    });
            //                }
            //                $scope.filterDataNature = tabData;
            //                $scope.$applyAsync();
            //            }else{
            //                util.alert(res.errMsg);
            //            }
            //        },
            //        error: function(){
            //            util.alert('系统维护，请稍候重试');
            //        }
            //    })
            //};
            //$scope.getFilterDataCities = function(){
            //    var url = api_prefix + "contract/get-contract-area-list";
            //
            //    $.ajax({
            //        url: url,
            //        type: 'get',
            //        dataType: 'json',
            //        success: function(res){
            //            if(res.retCode === "0"){
            //                var items = res.data;
            //                var tabData = [{value: '', name: '全部', selected: true}];
            //                var item;
            //                for (var i = 0; item = items[i]; i++) {
            //                    tabData.push({
            //                        value: item.areaId + '',
            //                        name: item.areaName
            //                    });
            //                }
            //                $scope.filterDataCities = tabData;
            //                $scope.$applyAsync();
            //            }else{
            //                util.alert(res.errMsg);
            //            }
            //        },
            //        error: function(res){
            //            util.alert('系统维护，请稍候重试');
            //        }
            //    })
            //};

            $scope.changePayway = function (status) {
                $scope.query.execute();
            };
            $scope.changeProductType = function (type) {
                $scope.query.execute();
            };
            $scope.changeRefundStatus = function (status) {
                $scope.query.execute();
            };

            /**
             * 判断查询时间
             * @param a
             * @param b
             * @returns {boolean}
             */
            var compareDate = function(a,b){
                var arrA = a.split("-");
                var start = new Date(arrA[0],arrA[1],arrA[2]);
                var startTime = start.getTime();

                var arrB = b.split("-");
                var end = new Date(arrB[0],arrB[1],arrB[2]);
                var endTime = end.getTime();

                if(startTime > endTime){
                    return true
                }else{
                    return false
                }
            };

            /**
             * 查询条件
             * @type {{keyword: string, beginDate: string, endDate: string, execute: Function}}
             */
            $scope.query = {
                keyword:'',
                beginDate: '',
                endDate: '',
                execute:function(page){
                    var pageInx = page || 1;
                    var parms = {
                        keyword: this.keyword,
                        beginDate: $scope.beginDate,
                        endDate: $scope.endDate,
                        pageIndex: pageInx,
                        pageSize: 10
                    };

                    if(compareDate(this.beginDate,this.endDate)){
                        util.alert('开始时间不得大于结束时间');
                        return
                    }

                    //收集过滤条件
                    var pay_way = $.grep($scope.pay_way, function(o, n){
                        return o.selected == true;
                    });
                    if(pay_way.length){
                        parms.pay_way = pay_way[0].value;
                    }

                    var productType = $.grep($scope.product_name, function(o, n){
                        return o.selected==true;
                    });
                    if(productType.length){
                        parms.product_name = productType[0].value;
                        $scope.pname = parms.product_name;
                    }
                    // todo parms.product_name == ''
                    $scope.productReadOnly = false;
                    if (parms.product_name == '移动工程协同充值卡' || parms.product_name == '云采购采宝') {
                        $scope.productReadOnly = false;
                        $scope.confirmDisabled = false;
                    }else{
                        $scope.productReadOnly = true;
                        $scope.confirmDisabled = true;
                    }

                    var refundStatus = $.grep($scope.refund_status, function(o, n){
                        return o.selected == true;
                    });
                    if(refundStatus.length){
                        parms.refund_status = refundStatus[0].value;
                    }

                    if (parms.beginDate == '' || parms.endDate == '') {
                        $scope.confirmDisabled = true;
                    }

                    $scope.exportData = parms;

                    console.log(parms);

                    var url = api_prefix + "contract/get-confirm-contract-list";

                    $.ajax({
                        url: url,
                        type: "get",
                        dataType: "json",
                        data: parms,
                        success: function (res) {
                            if(res.retCode === "0"){
                                var data = res.data;
                                $scope.contracts = data.items;
                                $scope.total = data.total;
                                $scope.total_pay_amount = data.total_pay_amount;

                                if ($scope.total == 0) {
                                    $scope.confirmDisabled = true;
                                }

                                if ($scope.total > 0 && !$scope.productReadOnly) {
                                    $scope.confirmDisabled = false;
                                }

                                $scope.qureyData = {
                                    contracts: data.items,
                                    total: data.total,
                                    beginDate: parms.beginDate,
                                    endDate: parms.endDate,
                                    totalpayamount: data.total_pay_amount,
                                    itemsall: data.itemsAll
                                };

                                $scope.$applyAsync();
                                $scope.getPage(pageInx);

                                console.log($scope.total_pay_amount);

                                $('.text-indent').append("&nbsp;&nbsp;<span>合计金额 "+$scope.total_pay_amount+" 元</span>");
                            }else{
                                util.alert(res.errMsg);
                            }
                        },
                        error: function(){
                            util.alert('系统维护，请稍候重试');
                        }
                    });
                }
            };


            $scope.onConfirmPaybackShow = function ($data, $dialog, $dialogScope, oldProd) {
                $dialogScope.oldProd = oldProd;
                var init = true;

                $dialogScope.$watch('data.authorization_numeric', function (itemVal) {
                    if (!$dialogScope.oldProd || !init) {
                        if ($dialogScope.data.min_number && parseInt($dialogScope.data.min_number) > 0) {
                            if (parseInt(itemVal) <= parseInt($dialogScope.data.min_number)) {
                                $dialogScope.data.amount = myMath.mul(itemVal, $dialogScope.data.min_price);
                            } else {
                                $dialogScope.data.amount = myMath.mul($dialogScope.data.min_number, $dialogScope.data.min_price) + myMath.mul(itemVal - $dialogScope.data.min_number, $dialogScope.data.price);
                            }
                        } else {
                            $dialogScope.data.amount = myMath.mul(itemVal, $dialogScope.data.price);
                        }
                    }
                });

                $dialogScope.ddlConfigProjects = {
                    allowClear: false,
                    data: $scope.ddlConfigProjectsData,
                    placeholder: '产品名称',
                    onchange2: function (item) {
                        $dialogScope.data.authorization_type = item.authorization_type;
                        $dialogScope.data.application_name = item.application_name;
                        $dialogScope.data.application_id = item.application_id;

                        if (!$dialogScope.oldProd || !init) {
                            $dialogScope.data.min_price = 0;
                            $dialogScope.data.price = 0;
                            $dialogScope.data.amount = 0;
                            $dialogScope.data.authorization_numeric = 0;
                            $dialogScope.data.custom_price = 0;
                        }

                        var appPrices = [],
                            array_appPrices;

                        array_appPrices = item.applicationPrices || [];
                        if (array_appPrices.length == 1) {
                            var eq0 = array_appPrices[0];
                            $dialogScope.data.unit = eq0.unit;
                            $dialogScope.data.price = eq0.price;
                            $dialogScope.data.min_price = eq0.min_price;
                            $dialogScope.data.min_number = eq0.min_number;
                            $dialogScope.data.custom_price = eq0.custom_price;
                        }

                        $.each(item.applicationPrices || [], function (i, d) {
                            appPrices.push({
                                id: d.unit,
                                text: d.unit,
                                price: d.price,
                                min_price: d.min_price,
                                min_number: d.min_number,
                                custom_price: d.custom_price
                            });
                        });

                        $dialogScope.ddlConfigSMSPrice = {
                            allowClear: false,
                            data: appPrices,
                            placeholder: '授权标准',
                            onchange2: function (price) {
                                $dialogScope.data.unit = price.text;
                                $dialogScope.data.price = price.price;
                                $dialogScope.data.min_price = price.min_price;
                                $dialogScope.data.min_number = price.min_number;
                                $dialogScope.data.custom_price = price.custom_price;

                                if (!$dialogScope.oldProd || !init) {
                                    $dialogScope.data.amount = 0;
                                    $dialogScope.data.authorization_numeric = 0;
                                }

                                if ($dialogScope.oldProd && $dialogScope.data.custom_price == 1) {
                                    $dialogScope.data.price = $dialogScope.oldProd.price;
                                }

                                init = false;
                            }
                        };
                        $dialogScope.$applyAsync();
                    }
                };
            };

            $scope.ConfirmPayback = function ($data, $dialog, $dialogScope) {
                console.log($data);
            };

            //翻页控件
            $scope.getPage = function(page){
                var pageInx = page || 1;
                $scope.startPageIndex = (pageInx - 1)*10;
                $('#pagination').pagination($scope.total, $scope.total_pay_amount, {
                    current_page: pageInx - 1,
                    num_edge_entries: 1, //边缘页数
                    num_display_entries: 4, //主体页数
                    show_total_amount: true, // 显示金额合计
                    callback: function (page_index, jq) {
                        $scope.startPageIndex = (page_index - 1)*10;
                        $scope.query.execute(page_index);
                    },
                    items_per_page: 10 //每页显示1项
                });
            };

            /**
             * 导入结算状态
             */
            $('#importBalance').fileupload({
                dataType: 'json',
                url: api_prefix + "contract/import-balance-contract-list-execl",
                acceptFileTypes: /(\.|\/)(xls?x)$/i,
                maxFileSize: 10000000,
                done: function (e, data) {
                    var res = data.result;
                    if(res.retCode == '0'){
                        util.alert('导入结算状态成功');
                        $scope.query.execute();
                    }else{
                        util.alert(res.errMsg);
                    }
                },
                fail: function(e, data) {
                    util.alert('系统维护，请稍候重试');
                }
            });

            /**
             * 导出
             */
            $scope.exportData = {
                areaId: '',
                beginDate: '',
                endDate: '',
                keyword: '',
                pageIndex: 1,
                pageSize: 10,
                property: '',
                status: ''
            };
            $scope.export = function(){
                util.confirm('确定要导出数据吗？',{
                    ok:function(){
                        var url = api_prefix + "contract/export-balance-contract-list-execl";
                        var data = $scope.exportData;
                        util.download(url,data);
                    }
                });
            };

            // 获取查询条件
            $scope.getQueryParams = function(page) {
                var pageInx = page || 1;
                var parms = {
                    keyword: this.keyword,
                    beginDate: $scope.beginDate,
                    endDate: $scope.endDate,
                    pageIndex: pageInx,
                    pageSize: 10
                };

                parms.pageIndex = page || 1;
                parms.pageSize = config.pager().pageSize;

                var pay_way = $.grep($scope.pay_way, function(o, n){
                    return o.selected == true;
                });
                if(pay_way.length){
                    parms.pay_way = pay_way[0].value;
                }

                var productType = $.grep($scope.product_name, function(o, n){
                    return o.selected==true;
                });
                if(productType.length){
                    parms.product_name = productType[0].value;
                }

                var refundStatus = $.grep($scope.refund_status, function(o, n){
                    return o.selected == true;
                });
                if(refundStatus.length){
                    parms.refund_status = refundStatus[0].value;
                }

                return parms;
            };

            // 导出列表
            $scope.exportPaymentList = function() {
                //console.log($scope.exportData);
                util.confirm('确定要导出数据吗？', {
                    ok: function () {
                        var parms = $scope.exportData;//$scope.getQueryParams();
                        delete parms.pageIndex;
                        delete parms.pageSize;
                        delete parms.sortBy;
                        delete parms.sortAsc;
                        var url = api_prefix + '/contract/export-confirm-payment-list';
                        util.download(url, parms);
                        console.log(parms);
                    }
                });
            };

            /**
             * 页面初始化
             */
            $scope.init = function(){
                //$scope.getFilterDataNature();
                //$scope.getFilterDataCities();
                $scope.query.execute();
            };
            $scope.init();
        }]);
});